# -*- coding: utf-8 -*-
import sys

if 'threading' in sys.modules: del sys.modules['threading']
from gevent import monkey

monkey.patch_socket()
monkey.patch_ssl()
from gevent.server import StreamServer
import json
import logging
from logging.handlers import RotatingFileHandler
from mqtt import push_mqtt
from apns import push_apns

try:
    import setting
except ImportError:
    import sys

    sys.path.append('..')
    import setting

from core.cache import redis


def handle(sock, address):
    try:
        data = sock.recv(4096)
        if not data:
            return None
        data = json.loads(data)
        payload = data['data']
        tokenlist = []
        for userid in data['family']:
            userid = str(userid)
            appletoken, version = redis.hmget('User:' + userid, 'appletoken', 'version')
            if appletoken:
                tokenlist.append((appletoken, version))
            push_mqtt(userid, payload)
        if tokenlist:
            push_apns(tokenlist, payload)
    except:
        logger.error('', exc_info=True)
    finally:
        sock.close()


logger = logging.getLogger('push')
logfile = setting.push['logfile']
File_logging = RotatingFileHandler(logfile, maxBytes=10 * 1024 * 1024, backupCount=50)
File_logging.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
File_logging.setLevel(setting.push['loglevel'])
logger.addHandler(File_logging)
logger.setLevel(setting.push['loglevel'])
apnslog = logging.getLogger('apnsclient')
apnslog.addHandler(File_logging)
apnslog.setLevel(setting.push['loglevel'])

if __name__ == '__main__':
    import os

    os.popen('echo %s > %s' % (os.getpid(), setting.push['pid']))
    server = StreamServer(('127.0.0.1', setting.push['port']), handle, backlog=100000)
    server.serve_forever()
